package com.zhugang.week13.prefixsuffixstatistics;

/**
 * @program algorithms
 * @description: trap
 * @author: chanzhugang
 * @create: 2022/09/23 23:30
 */
public class Trap {

    /**
     * 42 接雨水
     * https://leetcode.cn/problems/trapping-rain-water/
     * O(n^2)
     *
     * @param height
     * @return
     */
    public int trap(int[] height) {
        // 暴力求解
        // 每个柱子盛水量 ：min(maxLeft, maxRight) - 当前柱子高度
        int n = height.length;
        int carryTotal = 0;
        for (int i = 1; i < n; i++) {

            int maxLeft = 0;
            for (int j = 0; j < i; j++) {
                // 左边最高的柱子
                maxLeft = Math.max(maxLeft, height[j]);
            }

            int maxRight = 0;
            for (int j = i + 1; j < n; j++) {
                // 右边最高的柱子
                maxRight = Math.max(maxRight, height[j]);
            }

            int carry = Math.min(maxLeft, maxRight) - height[i];
            if (carry < 0) {
                carry = 0;
            }
            carryTotal += carry;
        }
        return carryTotal;
    }

    /**
     * O(n)
     *
     * @param height
     * @return
     */
    public int trap2(int[] height) {
        // 前缀、后缀统计
        int n = height.length;
        int[] leftMax = new int[n];
        int max = 0;
        for (int i = 0; i < n; i++) {
            // 左边最大值
            leftMax[i] = Math.max(max, height[i]);
            max = leftMax[i];
        }

        int[] rightMax = new int[n];
        max = 0;

        for (int i = n - 1; i >= 0; i--) {
            // 右边最大值
            rightMax[i] = Math.max(max, height[i]);
            max = rightMax[i];
        }

        int carryTotal = 0;
        for (int i = 0; i < n; i++) {
            // 总的接雨水量
            carryTotal += Math.min(leftMax[i], rightMax[i]) - height[i];
        }
        return carryTotal;
    }
}